// algowala.cc
//
// by jag bot
//

#include <iostream>
#include <iomanip>
#include <iterator>
#include <fstream>
#include <string>
#include <list>
#include <algorithm>
#include <signal.h>
#include <stdlib.h>
#include "chrono.h"
#include "stock.h"
#include "ansi_color_codes.h"

using namespace std;


struct name_out {
  
  ofstream& f;
  
  name_out (ofstream& _f) : f(_f) {}
  void operator() (const stock& s) {
    f << s.name << "\t";
  }
  
};

struct price_out {
  
  ofstream& f;
  int endln;
  
  price_out (ofstream& _f) : f(_f) {}
  void operator() (const stock& s) {
    f << s.price << "\t";
  }
  
};

void ctrl_c_pressed (int signum) {
  cout << endl << "ctrl + c pressed" << endl;
  cout << "converting to R script" << endl;
  system ("tclsh remove-trailing-tabs.tcl > for-r-notabs");
  system ("tclsh tor.tcl > plot.r");
  cout << "conversion to R script complete";
  exit (signum);
}

int main (int argc, char* argv[]) {
  
  // output stock data so we can plot a pic with R language used widely in quantitative finance
  ofstream file ("for-r", ios::out); 
  file << setprecision (6); // upto 6 decimal places
  
  signal (SIGINT, ctrl_c_pressed); // handle ctrl+c as we infinite loop (see below)

  chrono clk; // our nanosecond precise clock!
  
  list<stock> stocks; // list of stocks
  
  // add a couple stocks
  //
  // name, price, volatility, how many times to update, in how many seconds
  stock rbs ("RBS", 65, 10, 1, 1); // RBS, 65p, price moves by upto 10p every change, change once, every second
  stock barclays ("BARC", 220, 10, 3, 5); // BARC, 220p, price moves by upto 10p every change, change 3 times, every 5 seconds 
  stock hsbc ("HSBC", 540, 50, 1, 1); // HSBC, 540p, price moves by upto 50p every change, change once, every second
  
  stocks.push_back (rbs);
  stocks.push_back (barclays);
  stocks.push_back (hsbc);
  
  // put out stock name in for-r file

  for_each (stocks.begin (), stocks.end (), name_out (file));
  file << endl;
  
  clk.reset (); // get ready to tick
  double t0 = clk.secs, t1 = t0;
  while (1) {
    for (list<stock>::iterator i = stocks.begin (), j = stocks.end (); i != j; ++i) { // run thru list of stocks and tick each
      stock& si = *i;
      si.tick (clk.secs);
    }
    
    t1 = clk.secs;
    float dt = t1 - t0;
    if ( dt > 1) { // output stock price every second for graphing in R
      t0 = t1;
      for_each (stocks.begin (), stocks.end (), price_out (file));
      file << endl;
    }

    clk.tick ();
    
  }
  return 0;

}
